<template>
  <view class="upgrade-modal" :class="show === true ? 'show' : ''">
    <view class="upgrade-dialog" style="background-color: transparent;">
      <view class="padding-top text-white" :class="'upgrade-topbg-'+theme">
        <view>
          <text class="upgrade-title">{{ title }}</text>
        </view>
        <text class="flex-wrap">{{ version }}</text>
      </view>
      <view class="padding-xl bg-white text-left">
        <scroll-view style="max-height: 200rpx;" scroll-y="auto">
          <view style="font-size: 15px;">{{ upgradeTitle }}</view>
          <text style="font-size: 11px;margin-top: 10upx;">{{ upgradeContent }}</text>
        </scroll-view>
        <view class="upgrade-progress radius striped active" v-if="showProgressBar">
          <view :class="'bg-'+theme" :style="'width: '+upgradeProcess+'%;'">
            {{ upgradeProcess }}
          </view>
        </view>
      </view>
      <view class="upgrade-bar bg-white justify-end">
        <view class="action" v-if="upgrade === true">
          <button class="upgrade-btn" :class="'bg-'+theme" v-if="showProgressBar === false"
            @click="handleUpgrade">{{ $t('component.upgradeCenterApp.confirmUpgradeText') }}</button>
          <button class="upgrade-btn margin-left" :class="'line-'+theme" v-if="showProgressBar === false"
            @click="upgradeCancel">{{ $t('component.upgradeCenterApp.cancelUpgradeText') }}</button>
        </view>
        <view class="action text-center" v-if="showProgressBar === true && upgradeForce === false">
          <button class="upgrade-btn" :class="'bg-'+theme"
            @click="upgradeBreak">{{ $t('component.upgradeCenterApp.interruptUpgradeText') }}</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import request from '@/utils/http/uni-ajax';
  export default {
    name: 'UpgradeCenter',
    props: {
      /** 主题，目前支持green,pink,blue,yellow,red */
      theme: {
        type: String,
        default: 'blue'
      },
      /** 当前应用信息 */
      appInfo: {
        type: Object,
        default: () => {
          return {
            /** 当前应用的APPID */
            AppId: '',
            /** 当前应用的名称 */
            Name: '',
            /** 当前应用的描述 */
            Descript: '',
            /** 当前应用的版本名称 */
            Version: '',
            /** 当前应用的版本号 */
            VersionCode: '',
            /** 当前应用的作者 */
            Author: '',
            /** 当前应用的电子邮箱 */
            Email: '',
            /** 客户端平台，值域为：ios、android、mac（3.1.10+）、windows（3.1.10+）、linux（3.1.10+） */
            Platform: '',
          }
        }
      },
      /** 升级检测url */
      url: {
        type: String,
        default: ''
      },
      /** appstore连接，如果启用，由服务端返回appstore的地址 */
      appStoreLink: {
        type: Boolean,
        default: false
      },
      /** 是否页面截入时就判断升级 */
      autoCheck: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        /** 显示升级模态窗口 */
        show: false,
        title: '',
        // // 当前应用信息
        // appInfo: {
        // 	AppId: '',	//当前应用的APPID
        // 	Name: '',	//当前应用的名称
        // 	Descript: '',	//当前应用的描述
        // 	Version: '',	//当前应用的版本名称
        // 	VersionCode: '',	//当前应用的版本号
        // 	Author: '',	//当前应用的作者
        // 	Email: '',	//当前应用的电子邮箱
        // 	Platform: '',	//客户端平台，值域为：ios、android、mac（3.1.10+）、windows（3.1.10+）、linux（3.1.10+）
        // },
        /** 是否需要升级 */
        upgrade: false,
        /** 强制升级 */
        upgradeForce: false,
        /** 静默升级 */
        upgradeSilent: false,
        /** 是否Wgt(增量)升级 */
        upgradeWgt: false,
        /** 升级大小 */
        upgradeSize: 0,
        /** 升级版本名称 */
        upgradeVersion: '',
        /** 升级版本号 */
        upgradeVersionCode: '',
        /** 升级作者 */
        upgradeAuthor: '',
        /** 升级电子邮箱 */
        upgradeEmail: '',
        /** 升级URL */
        upgradeUrl: '',
        /** 升级标题 */
        upgradeTitle: '',
        /** 升级内容 */
        upgradeContent: '',
        /** 显示进度条 */
        showProgressBar: false,
        /** 升级进度条 */
        upgradeProcess: 0,
        /** 下载任务 */
        downloadTask: null,
      }
    },
    // 页面截入时
    async mounted() {
      const that = this; //解决在mounted()获取不到data中的数据
      this.$nextTick(async function() {
        // 仅在整个视图都被渲染之后才会运行的代码
        that.title = this.$t('component.upgradeCenterApp.checkingText');
        let getedAppInfo = false;
        if (that.appInfo && that.appInfo.AppId && that.appInfo.Version && that.appInfo.VersionCode && that
          .appInfo.Platform) {
          getedAppInfo = true;
        }
        // #ifdef APP-PLUS
        if (!getedAppInfo) {
          plus.runtime.getProperty(plus.runtime.appid, async function(widgetInfo) {
            // uni.showModal({
            //     title: 'mounted',
            //     content: JSON.stringify(widgetInfo)
            // });
            that.appInfo.AppId = widgetInfo.appid;
            that.appInfo.Name = widgetInfo.name;
            that.appInfo.Descript = widgetInfo.descript;
            that.appInfo.Version = widgetInfo.version;
            that.appInfo.VersionCode = widgetInfo.versionCode;
            that.appInfo.Author = widgetInfo.author;
            that.appInfo.Email = widgetInfo.email;
            that.appInfo.Platform = uni.getSystemInfoSync().platform;

            if (that.autoCheck) {
              // console.log('mounted_APP_AutoCheck', that.appInfo);
              await that.checkUpgrade();
            }
          });
        } else {
          if (that.autoCheck) {
            // console.log('mounted_AutoCheck', that.appInfo);
            await that.checkUpgrade();
          }
        }
        // #endif
        // #ifndef APP-PLUS
        if (that.autoCheck) {
          // console.log('mounted_AutoCheck', that.appInfo);
          await that.checkUpgrade();
        }
        // #endif
      });
    },
    computed: {
      version() {
        let retversion = '';
        retversion =
          `${this.appInfo.Version}${this.appInfo.Version != '' && this.upgradeVersion != '' ? '->' : ''}${this.upgradeVersion}`;
        return retversion;
      }
    },
    methods: {
      /** 检测升级 */
      async checkUpgrade() {
        const that = this;
        let resultDto = null;
        try {
          uni.showLoading({
            title: this.$t('common.loadingText'),
            mask: true
          });
          if (that.url && that.url !== '') {
            const dto = {
              Code: that.appInfo.AppId,
              Platform: that.appInfo.Platform
            };
            const result = await request.post({
              url: that.url,
              data: dto,
              requestOptions: {
                errorMessageMode: 'message'
              },
            });
            if (result.Type === 200 && result.Data) {
              uni.hideLoading();
              resultDto = result.Data;
              that.upgrade = resultDto.Enabled && resultDto.VersionCode !== that.appInfo.VersionCode;
              resultDto.Upgrade = that.upgrade;
              if (that.upgrade === true) {
                that.title = this.$t('component.upgradeCenterApp.newVersionText');

                that.upgradeForce = resultDto.Force;
                that.upgradeSilent = resultDto.Silent;

                that.appStoreLink = resultDto.AppStoreLink;

                that.upgradeWgt = resultDto.Wgt;
                if (resultDto.Size > 0) {
                  that.upgradeSize = resultDto.Size;
                }
                that.upgradeVersion = resultDto.Version;
                that.upgradeVersionCode = resultDto.VersionCode;
                that.upgradeAuthor = resultDto.Author;
                that.upgradeEmail = resultDto.Email;

                that.upgradeUrl = resultDto.Url;

                that.upgradeTitle = resultDto.Title;
                that.upgradeContent = resultDto.Content;

                if (that.upgradeSilent === true) {
                  that.show = false;
                } else {
                  that.show = true;
                }
                if (that.upgradeForce) {
                  await that.handleUpgrade();
                }

              } else {
                that.title = this.$t('component.upgradeCenterApp.latestVersionText');
              }
            }

          }

          uni.hideLoading();
          // uni.showToast({
          // 	title: this.$t('common.successText'),
          // 	icon: 'success',
          // 	duration: 2000
          // });
        } catch (err) {} finally {
          uni.hideLoading();
        }
        return resultDto;
      },
      /** 处理升级 */
      async handleUpgrade() {
        const that = this;
        that.showProgressBar = true;
        const platform = uni.getSystemInfoSync().platform;
        // console.log("操作系统：", platform);
        if (platform == 'ios' || that.appStoreLink) {
          //如果启用ios appstore升级，则打开appstore
          that.show = false;
          // console.log("跳转至appstore");
          // #ifdef APP-PLUS
          plus.runtime.launchApplication({
            action: that.upgradeUrl,
          }, function(e) {
            uni.showToast({
              title: this.$t('component.upgradeCenterApp.openAppStoreFailed'),
              icon: 'none'
            });
          });
          // #endif
        } else {
          const downloadurl = that.upgradeUrl;
          // console.log('handleUpgrade', downloadurl);
          const tempFilePath = await request.download({
            url: downloadurl,
            requestOptions: {
              errorMessageMode: 'modal'
            },
          }, (task) => {
            // console.log('handleUpgrade_Task', that.downloadTask);
            that.downloadTask = task;
            that.downloadTask.onProgressUpdate(function(res) {
              // console.log('handleUpgrade_Task_onProgressUpdate', res);
              that.upgradeProcess = res.progress;
              if (res.progress === Infinity) {
                //使用size计算
                // console.log("计算size");
                let progress = (res.totalBytesWritten / that.upgradeSize) * 100;
                if (progress > 100) {
                  progress = 100;
                }
                that.upgradeProcess = progress;
              }
            });
          });
          // console.log('handleUpgrade', tempFilePath);
          if (tempFilePath) {
            //开始安装
            // #ifdef APP-PLUS
            plus.runtime.install(tempFilePath, {
              // force: false
              force: true
            }, function() {
              // console.log('install success...');
              plus.runtime.restart();
            }, function(e) {
              // console.error('install fail...',e);
              uni.showModal({
                title: this.$t('component.upgradeCenterApp.installFailed'),
                content: JSON.stringify(e),
                showCancel: false
              });
            });
            // #endif
          }
        }
      },
      /** 取消升级 */
      async upgradeCancel() {
        const that = this;
        that.upgradeBreak();
        that.show = false;
      },
      /** 中断升级 */
      async upgradeBreak() {
        const that = this;
        if (that.downloadTask) {
          that.downloadTask.abort();
          that.downloadTask = null;
        }
        that.showProgressBar = false;
        that.upgradeProcess = 0;
      },
    }
  }
</script>

<style scoped>
  @import url('./upgrade.css');

  .upgrade-topbg-green {
    background-image: url('./images/green.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    height: 290rpx;
  }

  .upgrade-topbg-red {
    background-image: url('./images/red.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    height: 290rpx;
  }

  .upgrade-topbg-pink {
    background-image: url('./images/pink.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    height: 290rpx;
  }

  .upgrade-topbg-yellow {
    background-image: url('./images/yellow.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    height: 290rpx;
  }

  .upgrade-topbg-blue {
    background-image: url('./images/blue.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    height: 290rpx;
  }

  .upgrade-title {
    font-size: 50rpx;
    color: white;
  }
</style>
